#!/usr/bin/python
# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect

from former_project.business_logic.user import UserManager, \
    REDIRECT_FIELD_NAME, SESSION_KEY
from gateway.common_logic.const import USER

def login(request):
    if not request.POST:
        userinfo = UserManager.get_instance().get_userinfo(request)
        username = userinfo and userinfo[USER.USERNAME] or None
        data = {'username': username,
                'post_path': request.get_full_path()}
        return render_to_response('login.html', data)
    
    # login post back
    username = request.POST.get('username', None)
    password = request.POST.get('password', None)
    ip = request.META['REMOTE_ADDR']
    if not username or not password:
        return HttpResponse('Username or password must not be null!')
    r, session_id_or_msg = UserManager.get_instance().login(username, password, ip)
    if r == 0:
        redirect_to = request.GET.get(REDIRECT_FIELD_NAME, '/links/')
        response = HttpResponseRedirect(redirect_to)
        response.set_cookie(SESSION_KEY, session_id_or_msg)
        return response
    else:
        return HttpResponse(session_id_or_msg)

def logout(request):
    UserManager.get_instance().logout(request)
    response = HttpResponseRedirect('/login/')
    response.delete_cookie(SESSION_KEY)
    return response
